#!/usr/bin/env python
# -*- coding: UTF-8 -*-


import sys
import os
import time
import glob
from print_r import print_r

from lib.kernel import core
from lib.func_ext import *
from lib.config import config


class Process(object):
    def __init__(self):
        self.cwd = os.getcwd()
        self.setting = config().setting()
        self.db = core().database('shopex_certi')
        self.app_list = self.get_app_list()
        self.format = []

    def main(self,params):
        #self.api = params['api'].replace('_','.')
        self.adapter = params['adapter']
        self.file = '%s.csv' % self.adapter
        self.dir = params['dir']
        os.chdir(self.dir)
        file = glob.glob('store_*.py')
        for l in file:
            api = os.path.splitext(l)[0].replace('_','.')
            self.check(api)
        os.chdir(self.cwd)
        self.tofile()

    def check(self,api):
        sql = '''
            SELECT * FROM `svc_app_instance_list`
            WHERE `app_instance_id`='store.promotion.add'
            AND `status`='true' AND `app_key`='shopex_b2b' AND `method`='response'
        '''
        row = self.db.selectRow(sql)
        if row:
            sql = '''
                SELECT `app_key` FROM `svc_app_instance_list`
                WHERE `app_instance_id`='store.promotion.add'
                AND `status`='true' AND `app_key`!='%(adapter)s' AND `method`='request'
            ''' % {'adapter':self.adapter}
            lists = self.db.select(sql)
            self.format.append('[%s]' % (api))
            for app in lists:
                if app['app_key'] in self.app_list:
                    name,result = self.app_list[app['app_key']],'ok'
                else:
                    name,result = '-','fail'
                f = '%s[%s],%s,%s' % (app['app_key'],name,self.adapter,result)
                self.format.append(f)
            self.format.append('\n')

    def tofile(self):
        fp = open(self.file,'wb')
        for l in self.format:
            s = l.decode('UTF-8').encode('GBK')
            fp.write(s+'\n')
        fp.close()

    def get_app_list(self):
        sql = "SELECT `app_key`,`app_name` FROM `svc_app_list` WHERE `status`='true'"
        row = self.db.select(sql)
        tmp = {}
        for v in row:
            tmp[v['app_key']] = v['app_name']
        return tmp


if __name__ == '__main__' :
    start = time.time()
    main()
    end = time.time()
    print 'spend time is %ss' % (end-start)